package tests_dao;

import java.math.BigDecimal;
import java.text.ParseException;
import java.util.Date;

import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.testng.Assert;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

import dao.CrudServiceImpl;
import entities.Currency;
import entities.ExchangeRate;

public class DirtyCheckingTest
{
	CrudServiceImpl crud_service = new CrudServiceImpl(); 
	
	@Test
	public void dirtyCheckingTest ()
	{
		final String query = "from ExchangeRate where id in (select min(id) from ExchangeRate)";
		int begin_conversion;
		int end_conversion;
		
		Session session = new Configuration().configure().buildSessionFactory().openSession();
		Transaction transaction = session.beginTransaction();
		
		
		
		ExchangeRate result = (ExchangeRate) session.createQuery(query).uniqueResult();
		begin_conversion = result.getConversion();
		
		result.setConversion(begin_conversion + 1);
		transaction.commit();
		
		transaction.begin();
		result = (ExchangeRate) session.createQuery(query).uniqueResult();
		end_conversion = result.getConversion();
		transaction.commit();
		
		session.close();
		
		
		Assert.assertEquals(end_conversion, begin_conversion+1);
		
		
		
	}
	
	
	
	@BeforeTest
	public void beforeTest()
	{
		crud_service.clearDataBase();
		Currency abc = new Currency("abc", "abc currency");
		crud_service.addCurrency(abc);
		crud_service.addExchangeRate(new ExchangeRate(new Date(), abc, 1, new BigDecimal(6)));
	}
	
	@AfterTest
	public void afterTest()
	{
		crud_service.clearDataBase();
	}

}
